#!usr/bin/env python

"""
This script installs or uninstalls YouPyStream on your system.
-------------------------------------------------------------------------------
Usage: install.py [OPTIONS] COMMAND

Commands:
	install                  Install to /usr/local

	uninstall				 Uninstall from /usr/local

	make_dist                Create source distribution

Options:
	--dir <directory>		 Install or uninstall in <directory>
							 instead of /usr/local
"""

import os
import sys
import getopt
import shutil
from src import const

source_dir = os.path.dirname(os.path.realpath(__file__))
install_dir = '/usr/local/'

#Files to be installed, as (source file, destination directory)
FILES = (('src/playertool.py', 'share/youpystream/src'),
		 ('src/youpystream.py', 'share/youpystream/src'),
		 ('src/youtube-dl', 'share/youpystream/src'),
		 ('src/__init__.py','share/youpystream/src'),
		 ('src/vlc.py', 'share/youpystream/src'),
		 ('src/download.py','share/youpystream/src'),
		 ('src/playlist.py','share/youpystream/src'),
		 ('src/data/icon.png', 'share/youpystream/src/data'),
		 ('src/data/youpystream.glade', 'share/youpystream/src/data'))

FILES_TAR = (('install.py'),
	         ('README'))

#Symlinks to be created as (target, symlink)
LINKS = (('../share/youpystream/src/youpystream.py', 'bin/youpystream'),)

def info():
	"""Print usage info and exit."""
	print __doc__
	sys.exit(1)

def install(src, dst):
	"""Copy <src> to <dst>. The <src> path is relative to the source_dir and
	the <dst> path is a directory relative to the install_dir.
	"""
	try:
		dst = os.path.join(install_dir, dst, os.path.basename(src))
		src = os.path.join(source_dir, src)
		assert os.path.isfile(src)
		assert not os.path.isdir(src)
		if not os.path.isdir(os.path.dirname(dst)):
			os.makedirs(os.path.dirname(dst))
		shutil.copy(src, dst)
		print 'Installed', dst
	except Exception:
		print 'Could not install', dst

def uninstall(path):
	"""Remove the file or directory at <path>, wich is relative to the
	install_dir.
	"""
	try:
		path = os.path.join(install_dir, path)
		if os.path.isfile(path) or os.path.islink(path):
			os.remove(path)
		elif os.path.isdir(path):
			shutil.rmtree(path)
		else:
			return
		print 'Removed', path
	except Exception:
		print 'Could not remove', path

def make_link(src, link):
	"""Create a symlink <link> pointing to <src>. The <link> path is relative
	to the install_dir, and the <src> path is relative to the full path of
	the created link.
	"""
	try:
		link = os.path.join(install_dir, link)
		if os.path.isfile(link) or os.path.islink(link):
			os.remove(link)
		if not os.path.exists(os.path.dirname(link)):
			os.makedirs(os.path.dirname(link))
		os.symlink(src, link)
		print 'Symlinked', link
	except:
		print 'Could not create symlink', link

def check_dependencies():
	"""Check for required and recommended dependencies"""
	required_found = True
	recommended_found = True
	print 'Checking dependencies ...\n'
	print 'Required dependencies:'
	
	#PyGtk
	try:
		import pygtk
		print 'pygtk : Ok'
	except ImportError:
		print 'pygtk : Not found'
		required_found = False
	#Gdata
	try:
		import gdata.youtube
		print 'gdata : Ok'
	except ImportError:
		print 'gdata : Not found'
		required_found = False

	if not required_found:
		print '\nCould not find all required dependencies!'
		print 'Please install them and try again.'
		sys.exit(1)

#Parse the command line
try:
	opts, args = getopt.gnu_getopt(sys.argv[1:], '', ['dir='])
except getopt.GetOptError:
	info()
for opt, value in opts:
	if opt == '--dir':
		install_dir = value
		if not os.path.isdir(install_dir):
			print '\nError', install_dir, 'does not exist.'
			info()

#install youpystream
if args == ['install']:
	check_dependencies()
	print 'Installing YouPyStream to', install_dir, '..\n'
	if not os.access(install_dir, os.W_OK):
		print 'You do not have wrute permissions to', install_dir
		sys.exit(1)
	for src, dst in FILES:
		install(src, dst)
	for src, link in LINKS:
		make_link(src,link)
elif args == ['uninstall']:
	print 'Uninstalling YouPyStream from', install_dir, '...\n'
	uninstall('share/youpystream')
	for _, link in LINKS:
		uninstall(link)
elif args == ['make_dist']:
	version = const.__version__
	if sys.platform == 'win32':
		pass
	else:
		try:
			import tarfile
			try:
				os.makedirs('dist')
			except:
				pass
			tar = tarfile.open('dist/youpystream-'+version+'.tar.gz','w:gz')
			for src,_ in FILES:
				tar.add(src)
			for src in FILES_TAR:
				tar.add(src)
			tar.close()
		except:
			print '\nCreate source dist failed'
else:
	info()
